package com.github.binarywang.demo.wx.mp.service.oss;

import cn.soilove.oss.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * oss存储
 *
 * @author xiaoban
 * @date 2021/7/2 下午6:36
 */
@Service
@Slf4j
@ComponentScan("cn.soilove")
public class AliOssServiceImpl implements AliOssService {

    @Autowired
    private OssService ossService;

    /**
     * 网络图片上传
     *
     * @param url url
     * @return {@link String}
     */
    private String uploadNetWorkImage(String name, String url){
        return ossService.upload4url(name,url);
    }

    @Override
    public String upload(String name, String filePath) {
        return upload(name,new File(filePath));
    }

    @Override
    public String upload(String name, InputStream in, Long fileLength) {
        byte[] b =new byte[fileLength.intValue()];
        try {
            in.read(b);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ossService.upload4bytes(name, b);

    }

    @Override
    public String upload(String name, File file) {
        if (file == null||!file.exists()) {
            return null;
        }
        // 本地文件上传
        // byte[]数组上传
        InputStream in;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
       return upload(name,in,file.length());
    }

    /**
     * 上传
     *
     * @param name       的名字
     * @param filePath   文件路径
     * @param uploadType 上传类型
     * @return {@link String}
     */


    @Override
    public String upload(String name, String filePath, UploadType uploadType) {
        switch(uploadType){
            case LOCAL_FILE:
                return upload(name,new File(filePath));
            case NETWORK_IMAGE:
                return uploadNetWorkImage(name,filePath);
            case LOCAL_FILE_PATH:
                return upload(name,filePath);
        }
        InputStream in;
        // 文件流上传
        try {
            in = new FileInputStream(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return ossService.upload4inputStream(name,in);
    }
}
